package pers.ervinse.shoppingmall;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.regex.Pattern;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pers.ervinse.shoppingmall.domain.User;
import pers.ervinse.shoppingmall.domain.realUser;
import pers.ervinse.shoppingmall.utils.OkhttpUtils;
import pers.ervinse.shoppingmall.utils.PropertiesUtils;

/**
 * 注册页面
 */
public class RegisterActivity extends Activity {

    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Context mContext;

    private EditText register_login_name_et, register_login_password_et, register_email_et, register_verification_code_et;
    private Button register_btn, register_send_code_btn;

    private String userName, userPassword, userEmail, verificationCode;
    private boolean isEmailValid = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = this;

        // 初始化控件
        register_login_name_et = findViewById(R.id.register_login_name_et);
        register_login_password_et = findViewById(R.id.register_login_password_et);
        register_email_et = findViewById(R.id.register_email_et);
        register_verification_code_et = findViewById(R.id.register_verification_code_et);
        register_btn = findViewById(R.id.register_submit_btn);
        register_send_code_btn = findViewById(R.id.register_send_code_btn);

        // 初始状态禁用按钮
        register_btn.setEnabled(false);
        register_send_code_btn.setEnabled(false);
        register_verification_code_et.setEnabled(false);

        initListeners();
    }

    /**
     * 初始化监听器
     */
    private void initListeners() {
        // 邮箱输入框监听
        register_email_et.setOnFocusChangeListener((view, hasFocus) -> {
            if (!hasFocus) { // 输入框失去焦点时
                String email = register_email_et.getText().toString();
                isEmailValid = isValidEmail(email);
                if (isEmailValid) {
                    register_send_code_btn.setEnabled(true);
                } else {
                    register_send_code_btn.setEnabled(false);
                    Toast.makeText(mContext, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 发送验证码按钮监听
        register_send_code_btn.setOnClickListener(view -> {
            userEmail = register_email_et.getText().toString();
            sendVerificationCode(userEmail);
        });

        // 验证码输入校验
        register_verification_code_et.setOnFocusChangeListener((view, hasFocus) -> {
            if (!hasFocus) {
                checkAllInputs();
            }
        });

        // 注册按钮监听
        register_btn.setOnClickListener(view -> {
            userName = register_login_name_et.getText().toString();
            userPassword = register_login_password_et.getText().toString();
            verificationCode = register_verification_code_et.getText().toString();
            registerUser(userName, userPassword, userEmail, verificationCode);
        });

        // 输入框监听，检查是否启用注册按钮
        register_login_name_et.setOnFocusChangeListener((view, hasFocus) -> {
            if (!hasFocus) {
                checkAllInputs();
            }
        });

        register_login_password_et.setOnFocusChangeListener((view, hasFocus) -> {
            if (!hasFocus) {
                checkAllInputs();
            }
        });
    }

    /**
     * 检查所有必填字段是否填写以启用注册按钮
     */
    private void checkAllInputs() {
        String userName = register_login_name_et.getText().toString();
        String userPassword = register_login_password_et.getText().toString();
        String verificationCode = register_verification_code_et.getText().toString();

        boolean allFieldsFilled = !userName.isEmpty() && !userPassword.isEmpty() && isEmailValid && !verificationCode.isEmpty();
        register_btn.setEnabled(allFieldsFilled);
    }

    /**
     * 发送验证码
     *
     * @param email 用户输入的邮箱
     */
    private void sendVerificationCode(String email) {
        new Thread(() -> {
            try {
                Gson gson = new Gson();
                String url = PropertiesUtils.getUrl();

                // 构建请求参数
                FormBody formBody = new FormBody.Builder()
                        .add("email", email)
                        .build();

                Request request = new Request.Builder()
                        .url(url + "/users/sendCode")
                        .post(formBody)
                        .build();

                // 使用 OkHttp 发送请求
                OkHttpClient client = new OkHttpClient();
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    String responseString = response.body().string();
                    JsonObject responseObject = gson.fromJson(responseString, JsonObject.class);
                    boolean success = responseObject.get("status").getAsBoolean();
                    String message = responseObject.get("result").getAsString();
                    String verificationCode = responseObject.get("data").getAsString();

                    Looper.prepare();
                    if (success) {
                        // 存储验证码
                        SharedPreferences sharedPreferences = mContext.getSharedPreferences("APP_PREFS", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("verificationCode", verificationCode);
                        editor.apply();

                        Toast.makeText(mContext, "验证码已发送，请查收邮箱", Toast.LENGTH_SHORT).show();
                        runOnUiThread(() -> register_verification_code_et.setEnabled(true));
                    } else {
                        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
                    }
                    Looper.loop();
                } else {
                    Log.e(TAG, "请求失败，响应码: " + response.code());
                    Looper.prepare();
                    Toast.makeText(mContext, "网络请求失败", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 注册用户
     *
     * @param userName       用户名
     * @param userPassword   密码
     * @param userEmail      邮箱
     * @param verificationCode 用户输入的验证码
     */
    private void registerUser(String userName, String userPassword, String userEmail, String verificationCode) {
        // 获取存储的验证码
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("APP_PREFS", Context.MODE_PRIVATE);
        String storedCode = sharedPreferences.getString("verificationCode", "");

        if (!verificationCode.equals(storedCode)) {
            Looper.prepare();
            Toast.makeText(mContext, "验证码错误，请重新输入", Toast.LENGTH_SHORT).show();
            Looper.loop();
            return; // 验证码不正确，直接退出
        }

        // 验证码正确，继续注册流程
        new Thread(() -> {
            try {
                Gson gson = new Gson();
                realUser user = new realUser(0,userName, userPassword, 0,userEmail,null);
                JsonObject requestObject = new JsonObject();
                requestObject.add("user", gson.toJsonTree(user));
                requestObject.addProperty("verificationCode", verificationCode);

                String url = PropertiesUtils.getUrl();
                String responseJson = OkhttpUtils.doPost(url + "/users/register", requestObject.toString());
                JsonObject responseObject = gson.fromJson(responseJson, JsonObject.class);

                boolean status = responseObject.get("status").getAsBoolean();
                if (status) {
                    Intent intent = new Intent();
                    intent.putExtra("userName", userName);
                    intent.putExtra("userPassword", userPassword);
                    intent.putExtra("userEmail", userEmail);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    Looper.prepare();
                    Toast.makeText(mContext, "注册失败", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            } catch (IOException e) {
                e.printStackTrace();
                Looper.prepare();
                Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }).start();
    }

    /**
     * 验证邮箱格式
     *
     * @param email 邮箱地址
     * @return 是否为有效邮箱
     */
    private boolean isValidEmail(String email) {
        String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
        return Pattern.matches(emailPattern, email);
    }
}
